package com.pengtu.utils.jbpm.rollback;

import org.jbpm.api.Configuration;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.internal.log.Log;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.ProcessDefinitionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;

/**
 * 流程退回Listener
 * @author libitum
 *
 */
public class RollbackListener implements EventListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static ProcessEngine processEngine = Configuration
			.getProcessEngine();

	// 退回目的地，通过流程定义注入
	private String m_rollbackTo;

	/**
	 * 增加一条用于退回的路径
	 */
	@Override
	public void notify(EventListenerExecution execution) throws Exception {
		// TODO Auto-generated method stub
		ProcessInstance processInstance = execution.getProcessInstance();
		String processDefinitionId = processInstance.getProcessDefinitionId();
		ProcessDefinitionImpl processDefinition = (ProcessDefinitionImpl) processEngine
				.getRepositoryService().createProcessDefinitionQuery()
				.processDefinitionId(processDefinitionId).uniqueResult();
		
		ActivityImpl toActivityImpl = processDefinition.findActivity(m_rollbackTo);
		if(toActivityImpl == null){
			String msg = "In " + processDefinitionId + " no " + m_rollbackTo;
			Log.getLog(this.getClass().getName()).error(msg);
		}
		
		ActivityImpl fromActivityImpl = ((ExecutionImpl)execution).getActivity();
		
		TransitionImpl transition = fromActivityImpl.createOutgoingTransition();
		transition.setName(fromActivityImpl.getName() + " to " + m_rollbackTo);
		transition.setDestination(toActivityImpl);
	}

}
